﻿using DM_IBLL;
using DM_Sqlite.MappingClass;
using DM_TOOLS.Tools.SMTP;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Data;
using System.Reflection;

namespace DMSystem_Sqlite_WebAPI.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class User_PropsController : ControllerBase
    {
        private readonly ILogger<User_PropsController> _logger;
        private readonly IBLL_User iBLL_User;
        private readonly IBLL_Admin _bLL_Props_Admin;
        private readonly string controllerName;
        private readonly IMemoryCache _memoryCache;//内存缓存
        public User_PropsController(ILogger<User_PropsController> logger, IBLL_User bLL_User, IBLL_Admin bLL_Props_Admin, IMemoryCache memoryCache)
        {
            _logger = logger;
            iBLL_User = bLL_User;
            controllerName = GetType().Name;
            _bLL_Props_Admin = bLL_Props_Admin;
            _memoryCache = memoryCache;

        }
        [HttpGet]
        public IActionResult GetPropsUser(int page, int pagesize)
        {
            var data = iBLL_User.LoadEntities(a => true);

            var datacount = data.Count();

            var pagedata = data.Skip((page - 1) * pagesize).Take(pagesize).OrderBy(a => a.key);
            return Ok(new { pagedata, total = datacount });
        }


        [HttpPost]
        public IActionResult AddPropsUser([FromBody] dm_props_user row)
        {
            try
            {
                //先按照key来排序获得最后一个数据
                var last = iBLL_User.LoadEntities(a => true).OrderBy(a => a.key).LastOrDefault();
                if (last != null)
                {
                    //把要添加的数据的key改为最后一个数据的key+1，这样数据库里就是连续的数据，不会出现断档的key
                    row.key = last.key + 1;
                }
                else
                {
                    row.key = 1;
                }
                //^[a-zA-Z0-9,_]*$   只出现","或者"_"，不需要开头和结尾都是英文逗号，其他符号不准出现，数字字母没限制
                var isaddsucess = iBLL_User.AddEntity(row);
                var t = MethodBase.GetCurrentMethod();
                string? methodName = t?.Name;
                if (isaddsucess)
                {
                    _logger.LogInformation($"{controllerName}控制器{methodName}方法,执行成功：{DateTime.Now}");

                    return Ok("添加成功");
                }
                else
                {
                    _logger.LogError($"{controllerName}控制器{methodName}方法,执行失败-数据库操作失败：{DateTime.Now}");

                    return BadRequest("添加失败");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
          
        }
        [HttpPut]
        public IActionResult EditPropsUser([FromBody] dm_props_user row)
        {
            try
            {
                var t = MethodBase.GetCurrentMethod();
                string? methodName = t?.Name;
                var iseditsucess = iBLL_User.EditEntity(row);

                if (iseditsucess)
                {
                    _memoryCache.Remove(row.vehicle + "mailconfig");
                    _memoryCache.Remove(row.vehicle + "mailerror");
                    _memoryCache.Remove(row.vehicle + "sendtime");
                    _memoryCache.Remove(row.vehicle + "filename");
                    _memoryCache.Remove(row.vehicle + "logname");
                    _memoryCache.Remove(row.vehicle + DateTime.Now.ToString("MM-dd") + "sumdistance");
                    _memoryCache.Remove(row.vehicle + DateTime.Now.ToString("MM-dd") + "filecount");
                    _memoryCache.Remove(row.vehicle + DateTime.Now.ToString("MM-dd") + "readfilecount");
                    _memoryCache.Remove(row.vehicle + DateTime.Now.ToString("MM-dd") + "chanerrorcount");
                    _memoryCache.Remove(row.vehicle + DateTime.Now.ToString("MM-dd") + "readgpsfilecount");
                    _memoryCache.Remove(row.vehicle + DateTime.Now.ToString("MM-dd") + "gpserrorcount");
                    _memoryCache.Remove(row.watchpath);
                    _memoryCache.Remove(row.logpath);
                    _memoryCache.Remove(row.watchpath + "datetime");
                    _logger.LogInformation($"{controllerName}控制器{methodName}方法,执行成功：{DateTime.Now}");

                    return Ok("编辑成功");
                }
                else
                {
                    _logger.LogError($"{controllerName}控制器{methodName}方法,执行失败-数据库操作失败：{DateTime.Now}");

                    return BadRequest("编辑失败");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
    
            
        }
        [HttpDelete]
        public IActionResult DelPropsUser(int key)
        {
            try
            {
                var t = MethodBase.GetCurrentMethod();
                string? methodName = t?.Name;
                var data = iBLL_User.LoadEntities(a => true).Where(a => a.key == key).FirstOrDefault();

                if (data != null)
                {
                    var isdelsuccess = iBLL_User.DeleteEntity(data);
                    if (isdelsuccess)
                    {
                        _memoryCache.Remove(data.vehicle + "mailconfig");
                        _memoryCache.Remove(data.vehicle + "mailerror");
                        _memoryCache.Remove(data.vehicle + "sendtime");
                        _memoryCache.Remove(data.vehicle + "filename");
                        _memoryCache.Remove(data.vehicle + "logname");
                        _memoryCache.Remove(data.vehicle + DateTime.Now.ToString("MM-dd") + "sumdistance");
                        _memoryCache.Remove(data.vehicle + DateTime.Now.ToString("MM-dd") + "filecount");
                        _memoryCache.Remove(data.vehicle + DateTime.Now.ToString("MM-dd") + "readfilecount");
                        _memoryCache.Remove(data.vehicle + DateTime.Now.ToString("MM-dd") + "chanerrorcount");
                        _memoryCache.Remove(data.vehicle + DateTime.Now.ToString("MM-dd") + "readgpsfilecount");
                        _memoryCache.Remove(data.vehicle + DateTime.Now.ToString("MM-dd") + "gpserrorcount");
                        _memoryCache.Remove(data.watchpath);
                        _memoryCache.Remove(data.logpath);
                        _memoryCache.Remove(data.watchpath + "datetime");
                        _logger.LogInformation($"{controllerName}控制器{methodName}方法,参数为{key}执行成功：{DateTime.Now}");
                        return Ok("删除成功");
                    }
                    else
                    {
                        _logger.LogError($"{controllerName}控制器{methodName}方法,参数为{key}执行失败：{DateTime.Now}");
                        return BadRequest("删除失败");

                    }
                }
                else
                {
                    _logger.LogInformation($"{controllerName}控制器{methodName}方法,参数为{key}执行失败-找不到数据：{DateTime.Now}");
                    return BadRequest("数据库找不到数据");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 初始化一次“数据监控任务”的运行环境，并将用户和系统的监控配置保存到内存缓存中，供后台定时任务使用。
        /// </summary>
        /// <param name="dm_Props_User"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ExcuteDataMonitor(dm_props_user dm_Props_User)
        {
            try
            {
                //加载系统管理员配置
                var adminpara = _memoryCache.GetOrCreate<dm_props_admin>("datamonitoradminpara", value =>
                {
                    return _bLL_Props_Admin.LoadEntities(a => true).First();
                });
                //设置数据监控路径的缓存，用于定时数据监控任务时获得用户参数
                var userpara1 = _memoryCache.GetOrCreate<dm_props_user>(dm_Props_User.watchpath, value =>
                {
                    return dm_Props_User;
                });
                //设置日志监控路径的缓存，用于定时日志监控任务时获得用户参数
                var userpara2 = _memoryCache.GetOrCreate<dm_props_user>(dm_Props_User.logpath, value =>
                {
                    return dm_Props_User;
                });
                //记录哪一天开始的监控，然后到监控里去获取这个日期，把当前的日期到这个日期之间的缓存都删了
                _memoryCache.GetOrCreate<DateTime>(dm_Props_User.watchpath + "datetime", value =>
                {
                    return DateTime.Now;
                });
                //记录监控到的文件名
                _memoryCache.GetOrCreate<string>(dm_Props_User.watchpath + "filename", value =>
                {
                    return "";
                });
                //记录监控到的log文件名
                _memoryCache.GetOrCreate<string>(dm_Props_User.logpath + "logname", value =>
                {
                    return "";
                });
                _memoryCache.GetOrCreate<double>(dm_Props_User.vehicle + DateTime.Now.ToString("MM-dd") + "sumdistance", value =>
                {
                    return 0;
                });
                _memoryCache.GetOrCreate<int>(dm_Props_User.vehicle + DateTime.Now.ToString("MM-dd") + "filecount", value =>
                {
                    return 0;
                });

                if (adminpara != null && userpara1 != null && userpara2 != null)
                {
                    //创建邮件发送参数缓存
                    _memoryCache.GetOrCreate<SMTPConfig>(dm_Props_User.vehicle + "mailconfig", value =>
                    {
                        SMTPConfig sMTPConfig = new SMTPConfig();
                        sMTPConfig.subject = adminpara.subject;
                        sMTPConfig.emailtimespan = adminpara.timespan;
                        sMTPConfig.fromemail = adminpara.fromemail;
                        sMTPConfig.smtpaddress = adminpara.smtaddress;
                        sMTPConfig.modeltext = adminpara.modeltext;
                        sMTPConfig.autorizedkey = adminpara.autorizedkey;
                        sMTPConfig.smtpport = adminpara.smtpport;
                        sMTPConfig.toemail = dm_Props_User.email.Split(",");
                        sMTPConfig.fromname = dm_Props_User.person;
                        return sMTPConfig;
                    });

                    return Ok("点确定开始监控");
                }
                else
                {
                    return BadRequest("监控失败，请检查参数设置");
                }
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
            
        }
    }
}
